"use strict";

import axios from "axios";
import { ElMessage } from "element-plus";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.VUE_APP_BASE_URL || process.env.apiUrl || "/web/api",
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if (sessionStorage.token) {
      config.headers.Authorization = "Bearer " + sessionStorage.token;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    if (error.response.status === 422) {
      global.console.log(error.response.data.message);
      ElMessage({
        message: error.response.data.message,
        type: "error",
      });
    }
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(app) {
  Object.defineProperties(app.config.globalProperties, {
    axios: {
      get() {
        return _axios;
      },
    },
    $axios: {
      get() {
        return _axios;
      },
    },
    $http: {
      get() {
        return _axios;
      },
    },
  });

  // 添加全局的方法
  app.config.globalProperties.$translate = (key) => {
    // return key.split('.').reduce((o, i) => {
    //   if (o) return o[i]
    // }, i18n)
    return key;
  };
};

export default Plugin;
